package com.xxl.job.admin.core.util.alarm;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xxl.job.admin.core.alarm.impl.DingdingJobAlarm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author chenlinqing
 * @description:
 * @date: 2025/8/25 10:56
 */
@Component
public class DingDingAlarmUtil {
    private static Logger logger = LoggerFactory.getLogger(DingdingJobAlarm.class);
    private static ObjectMapper objectMapper = new ObjectMapper();


    public void sendMessage(String title, String alarmTo, String jobHandler, String jobDesc, String errorMsg) {
        try {

            if (StrUtil.isBlank(alarmTo)) {
                return;
            }

            String context = "定时任务handler：%s，\n 定时任务描述：%s \n 执行报错。错误日志如下：\n %s".formatted(jobHandler, jobDesc, errorMsg);
            // 发送POST请求
            HttpResponse response = HttpRequest.post(alarmTo)
                    .headerMap(getHeaders(), true)
                    .body(buildSendRequest(title, context))
                    .execute();

            String postResult = response.body();
            logger.info("DingDing send message result：{}", postResult);
            Map postResultMap = objectMapper.convertValue(postResult, Map.class);
            Object errCode = postResultMap.get("errcode");
            if (!Objects.equals(errCode, 0)) {
                throw new RuntimeException(postResult);
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 组装 DingTalkRequest
     *
     * @param title 标题
     * @param text  内容
     * @return DingTalkRequest
     */
    public String buildSendRequest(String title, String text) throws JsonProcessingException {
        Map<String, Object> message = new HashMap<>();
        message.put("msgtype", "markdown");
        Map<String, Object> markdown = new HashMap<>();
        markdown.put("text", StrUtil.sub(text, 0, 4000));
        markdown.put("title", title);
        message.put("markdown", markdown);

        // 处理提到的人
        Map<String, Object> at = new HashMap<>();
        at.put("isAtAll", true);
        message.put("at", at);
        return objectMapper.writeValueAsString(message);
    }


    public Map<String, String> getHeaders() {
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        return headers;
    }

}
